/****************************************************************************************
 * Copyright (c) 2010~2012 All Rights Reserved by
 * G-Net Integrated Service Co., Ltd. 
 ****************************************************************************************/
package com.kingtone.rongji;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.kingtone.rongji.tool.RongJiRestClient;
import com.kingtone.rongji.tool.RongJiUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**   
 * @Title:  XianYangPayActivity.java 
 * @author: wenhui.li 
 * @date:   2015-5-14 上午10:18:30   
 */
public class YinXinPayActivity extends BaseActivity
{
	private Context mContext = YinXinPayActivity.this ;
	private  TextView title = null;
	private  ImageView backBtn = null;
	private  Button payBtn = null;
	private  Button balanceBtn = null;
	private  EditText cardNo = null;
	private  EditText cardPwd = null;
	private  TextView resultTV = null;
	private String cardNoStr;
	private String cardPwdStr;
	private TextView orderAmountTV = null;
	private TextView cardDiscountTV = null;
	private String orderNum = null;
	private int orderType;
	
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		this.setContentView(R.layout.activity_yin_xin_pay);
		Intent intent = getIntent();
		if(intent.hasExtra("orderNo"))
		{
			orderNum = intent.getStringExtra("orderNo");
		}
		if(intent.hasExtra("orderType"))
		{
			orderType = intent.getIntExtra("orderType", 0);
		}
		setupView();
		getCardDiscount("29800215000000",orderNum); //商通卡默认号段
	}
	
	private void setupView()
	{
		title = (TextView)findViewById(R.id.title);
		title.setText(getString(R.string.pay_yinxin_title));
		
		backBtn = (ImageView)findViewById(R.id.back);
		backBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				onBackPressed();
			}
		});
		
		cardNo = (EditText)findViewById(R.id.yin_xin_card_num);
		cardPwd = (EditText)findViewById(R.id.yin_xin_card_pwd);
		
		resultTV = (TextView)findViewById(R.id.yin_xin_result);
		orderAmountTV = (TextView)findViewById(R.id.yin_xin_card_amount);
		cardDiscountTV = (TextView)findViewById(R.id.yin_xin_card_discount);
		
		payBtn = (Button)findViewById(R.id.yin_xin_pay_btn);
		payBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				verifyInput();
				cardPay(cardNoStr, orderNum, cardPwdStr);
			}
		});
		
		balanceBtn = (Button)findViewById(R.id.yin_xin_balance_btn);
		balanceBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				verifyInput();
				getCardBalance(cardNoStr,cardPwdStr);
			}
		});
	}
	
	private void verifyInput()
	{
		cardNoStr = cardNo.getText().toString();
		cardPwdStr = cardPwd.getText().toString();
		if(TextUtils.isEmpty(cardNoStr))
		{
			Toast.makeText(mContext, mContext.getString(R.string.card_input_card_no), Toast.LENGTH_SHORT).show();
			return;
		}
		if(TextUtils.isEmpty(cardPwdStr))
		{
			Toast.makeText(mContext, mContext.getString(R.string.card_input_card_pwd), Toast.LENGTH_SHORT).show();
			return;
		}
	}
	
	/**
	 * 获取订单金额、折扣等
	 * @param cardNo
	 * @param orderNo
	 */
	private void getCardDiscount(String cardNo, String orderNo)
	{
		RongJiRestClient.getCardDiscount(cardNo, orderNo, new AsyncHttpResponseHandler() {

			@Override
			public void onStart() {
				RongJiUtils.showEmptyProgress(mContext);
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				RongJiUtils.dismissProgress();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				RongJiUtils.dismissProgress();
				
				if(arg2 != null && !new String(arg2).equalsIgnoreCase("null"))
				{
					String result = new String(arg2);
					JSONTokener jsonParser = new JSONTokener(result);  
				    try {
						JSONObject obj = (JSONObject) jsonParser.nextValue();
						if(obj.has("OrderPayAmount"))
						{
							double orderAmount = obj.optDouble("OrderPayAmount"); //订单金额
							orderAmountTV.setText(Html.fromHtml(mContext.getString(R.string.order_count) + "<font color='##FD6B1F'>" + orderAmount +"</font>"));
						}
						double discount = 0.0;
						double payAmount = 0.0;
						if(obj.has("Dicount"))
						{
							discount = obj.optDouble("Dicount"); //享受的折扣
						}
						
						if(obj.has("ActualPayAmount"))
						{
							payAmount = obj.optDouble("ActualPayAmount"); //实际上你应付的金额
						}
						
						String str = mContext.getString(R.string.card_xian_xiang_discount) + "<font color='#FD6B1F'>" + discount +"</font>&nbsp;&nbsp;";
						str += mContext.getString(R.string.card_xian_xiang_pay_amount) + "<font color='#FD6B1F'>" + payAmount +"</font>";
						
						cardDiscountTV.setText(Html.fromHtml(str));
						
				    } catch (JSONException e) {
						e.printStackTrace();
					} 
				}
			}	
		});
	}
	
	/**
	 * 查询卡余额
	 * @param cardNo
	 * @param pwd
	 */
	private void getCardBalance(String cardNo, String pwd)
	{
		RongJiRestClient.getCardBalance(cardNo, pwd, new AsyncHttpResponseHandler() {

			@Override
			public void onStart() {
				RongJiUtils.showEmptyProgress(mContext);
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				RongJiUtils.dismissProgress();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				RongJiUtils.dismissProgress();
				
				if(arg2 != null && !new String(arg2).equalsIgnoreCase("null"))
				{
					String result = new String(arg2);
					JSONTokener jsonParser = new JSONTokener(result);  
				    try {
						JSONObject obj = (JSONObject) jsonParser.nextValue();
						boolean errorCode = obj.optBoolean("Status");
						if(errorCode)
						{
							String tag = obj.optString("Tag");
							resultTV.setText(mContext.getString(R.string.card_balance)  + tag);
							
						}else
						{
							String errorMsg = obj.optString("ErrorMessage");
							if(!TextUtils.isEmpty(errorMsg))
							{
								resultTV.setText(errorMsg);
							}
						}
				    } catch (JSONException e) {
						e.printStackTrace();
					} 
				}
			}	
		});
	}
	
	/**
	 * 卡支付
	 * @param cardNo
	 * @param orderNo
	 * @param cardPwd
	 */
	private void cardPay(String cardNo, String orderNo, String cardPwd)
	{
		RongJiRestClient.cardPay(cardNo, orderNo, cardPwd, new AsyncHttpResponseHandler() {

			@Override
			public void onStart() {
				RongJiUtils.showEmptyProgress(mContext);
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				String result = new String(arg2);
				Log.d("cardPay failure ", result);
				RongJiUtils.dismissProgress();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				RongJiUtils.dismissProgress();
				
				if(arg2 != null && !new String(arg2).equalsIgnoreCase("null"))
				{
					String result = new String(arg2);
					JSONTokener jsonParser = new JSONTokener(result);  
				    try {
						JSONObject address = (JSONObject) jsonParser.nextValue();
						boolean errorCode = address.optBoolean("Status");
						if(errorCode)
						{
							if(orderType == 6)
							{
								//加载WebView
								Intent intent = new Intent(mContext, SendFriendsActivity.class);
								intent.putExtra("orderNum", orderNum);
								startActivity(intent);
								finish();
							}else
							{
								//支付成功
								Intent intent = new Intent(YinXinPayActivity.this, CardPaySuccessActivity.class);
								intent.putExtra("orderNum", orderNum);
								startActivity(intent);
								finish();
							}
							
						}else
						{
							String errorMsg = address.optString("ErrorMessage");
							if(!TextUtils.isEmpty(errorMsg))
							{
								resultTV.setText(errorMsg);
							}
						}
				    } catch (JSONException e) {
						e.printStackTrace();
					} 
				}
			}	
		});
	}
}

